'use strict';

const Controller = require('egg').Controller;

class PostController extends Controller {
  async index() {
    const {ctx,app} = this;
    let option = ctx.helper.formatOptions(ctx.query,["postCode","postName","status"]);
    option.order = app.Sequelize.col("postSort");
    try {
      let result = await ctx.model.SysPost.findAndCountAll(option);
      ctx.body = ctx.helper.formateResponseList(result);
    } catch (error) {
      ctx.body = ctx.helper.formateResponse(null,"查询失败",310)
    }
  }
  async show(){
    const {ctx} = this;
    const {id} = ctx.params;
    const user = await ctx.model.SysPost.findByPk(Number(id));
    ctx.body = ctx.helper.formateResponse(user);
  }
  async update(){
    const {ctx} = this;
    const data = ctx.request.body;
    const user = ctx.session.userinfo;
    const post = await ctx.model.SysPost.findByPk(Number(data.postId));
    await post.update({
      postCode:data.postCode,
      postName:data.postName,
      postSort:data.postSort,
      remark:data.remark,
      status:data.status,
      updateBy:user.userName
    });
    ctx.body = ctx.helper.formateResponse(null);
  }
  async create(){
    const {ctx} = this;
    const data = ctx.request.body;
    const user = ctx.session.userinfo;
    await ctx.model.SysPost.create({
      postCode:data.postCode,
      postName:data.postName,
      postSort:data.postSort,
      remark:data.remark,
      status:data.status,
      createBy:user.userName,
      updateBy:user.userName
    });
    ctx.body = ctx.helper.formateResponse(null);
  }
  async destory(){
    const {ctx} = this;
    const {id} = ctx.params;
    const post = await ctx.model.SysPost.findByPk(Number(id));
    await post.destroy();
    ctx.body = ctx.helper.formateResponse(null);
  }
}

module.exports = PostController;
